package main

import (
	"log"
	"net"
	"os"
	"time"
)

func main() {
	// 配置日志格式，添加时间戳
	log.SetOutput(os.Stdout)
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)

	time.Sleep(2 * time.Second)

	// 测试带宽限制
	log.Println("\n测试带宽限制...")
	testBandwidthLimit()
}

// 测试带宽限制
func testBandwidthLimit() {
	//conn, err := net.Dial("tcp", "192.168.60.80:9000")
	conn, err := net.Dial("tcp", "localhost:9000")
	if err != nil {
		log.Fatal("无法连接到服务器:", err)
	}
	defer conn.Close()

	log.Println("已连接到服务器，开始测试带宽限制...")
	// 10MB数据
	dataSize := 50 * 1024 * 1024
	// 发送大量数据测试限流
	data := make([]byte, dataSize)
	for i := range data {
		data[i] = byte('A' + (i % 26))
	}

	startTime := time.Now()

	// 分批发送数据
	chunkSize := 8192
	totalSent := 0

	for totalSent < len(data) {
		end := totalSent + chunkSize
		if end > len(data) {
			end = len(data)
		}

		n, err := conn.Write(data[totalSent:end])
		if err != nil {
			log.Printf("发送数据时出错: %v", err)
			break
		}
		totalSent += n

		// 短暂延迟避免发送过快
		//time.Sleep(10 * time.Millisecond)
	}

	duration := time.Since(startTime)

	log.Printf("发送了 %d 字节数据\n", totalSent)
	log.Printf("耗时: %v\n", duration)
	log.Printf("平均速度: %.2f KB/s\n", float64(totalSent)/1024/duration.Seconds())
	log.Printf("平均速度: %.2f Mbps\n", float64(totalSent)*8/(1024*1024)/duration.Seconds())
	// 等待接收服务器的统计信息
	time.Sleep(1 * time.Second)
}
